package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    /**
     * 异步回调！
     * @param request
     * @return
     */
    @Operation(summary = "异步回调")
    @PostMapping("/notify")
    public Result wxNotify(HttpServletRequest request){
        System.out.println("异步回调成功!");
        //  调用服务层方法;
        Transaction transaction = wxPayService.wxNotify(request);
        //  声明一个map 集合
        Map<String,Object> result = new HashMap<>();
        //  判断支付状态！
        if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
            //  需要修改交易记录状态; 订单状态;
            wxPayService.updatePaymentInfoStatus(transaction);
            result.put("code", "SUCCESS");
            result.put("message", "成功");
            //  返回数据
            return Result.ok(result);
        }
        //返回失败
        result.put("code", "FAIL");
        result.put("message", "失败");
        return Result.fail(result);
    }
    /**
     * 查询支付结果
     * @param orderNo
     * @return
     */
//    @TsLogin
    @Operation(summary = "查询支付结果")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo) {
        //  调用微信接口查询支付状态
        Transaction transaction = wxPayService.queryPayStatus(orderNo);
        //  判断支付状态！
        if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
            //  需要修改交易记录状态; 订单状态;
            wxPayService.updatePaymentInfoStatus(transaction);
            //  返回数据
            return Result.ok();
        }
        //  返回数据
        return Result.fail();
    }

    /**
     * 微信支付
     * @param paymentType
     * @param orderNo
     * @return
     */
    @TsLogin
    @Operation(summary = "微信支付")
    @PostMapping("/createJsapi/{paymentType}/{orderNo}")
    public Result createJsapi(@PathVariable String paymentType,
                              @PathVariable String orderNo) {
        log.info("微信支付");
        //  获取用户Id
        Long userId = AuthContextHolder.getUserId();
        //  调用服务层方法
        Map<String,Object> map = wxPayService.createJsapi(paymentType, orderNo,userId);
        //  返回数据
        return Result.ok(map);
    }

}
